﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace VBAConvertor.Parsers
{
    class ForParser : ILineParser
    {
        private static readonly Regex ForPattern =
            new Regex(
                @"^For (?<var>[a-zA-Z][\w\$]*) = (?<from>.+) To (?<to>.+)( Step (?<step>[\w\$\-]+))?$",
                RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase | RegexOptions.Singleline);

        public string Parse(Stack<ParseStatus> statuses, string lineContent, LinesReader reader, out bool success, ref bool lineClosed)
        {
            var match = ForPattern.Match(lineContent);
            success = match.Success;
            if (!success) return lineContent;
            if (lineClosed || statuses.Peek().CurrentState == State.ClassDef)
            {
                throw new Exception();
            }
            lineClosed = true;
            statuses.Push(new ParseStatus {CurrentState = State.ForDef, StateInfo = match.Groups["var"].Value});
            var step = "1";
            if (!string.IsNullOrEmpty(match.Groups["step"].Value))
            {
                step = match.Groups["step"].Value;
            }
            int stepInt;
            var cmp = "<=";
            if (int.TryParse(step, out stepInt))
            {
                if (stepInt == 0)
                {
                    throw new Exception();
                }
                if (stepInt < 0)
                {
                    cmp = ">=";
                }
            }
            return string.Format("for (var {0} = {1}; {0} {4} {2}; {0}+={3}){{", match.Groups["var"].Value,
                                 match.Groups["from"].Value, match.Groups["to"].Value, step, cmp);
        }
    }
}
